<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SecurityHeaders
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $response = $next($request);

            // 防止点击劫持
            $response->headers->set('X-Frame-Options', 'DENY');
            
            // 防止MIME类型嗅探
            $response->headers->set('X-Content-Type-Options', 'nosniff');
            
            // 启用XSS保护
            $response->headers->set('X-XSS-Protection', '1; mode=block');
            
            // 引用策略
            $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
            
            // 权限策略
            $response->headers->set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
            
            // 内容安全策略（CSP）- 可以根据实际情况调整
            // 注意：CSP 可能会阻止前端请求，所以在开发环境不设置
            if (config('app.env') === 'production') {
                $response->headers->set(
                    'Content-Security-Policy',
                    "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self';"
                );
            }
            
            // HSTS - 仅在HTTPS环境下启用
            if ($request->secure()) {
                $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
            }

            return $response;
        } catch (\Exception $e) {
            \Log::error('SecurityHeaders中间件异常: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            // 如果设置安全头失败，继续处理请求
            return $next($request);
        }
    }
}

